<?php
namespace app\common\logic;
use app\common\model\ad\Ads;
use think\Db;
use think\Exception;
use app\common\logic\ad\Driver;
/**
 * Created by PhpStorm.
 * User: yangchunfu
 * Date: 2019/12/24
 * Time: 4:36 PM
 */

class AdHandler
{
    /**
     * @var array 广告的实例
     */
    public static $instance = [];
    /**
     * @var object 操作句柄
     */
    public static $handler;

    /**
     * 广告管理
     * @access public
     * @param  array       $options 配置数组
     * @param  bool|string $name     true 强制重新生成对象
     * @return Driver
     */
    public static function create(array $options = [], $name = false)
    {

        $type = $options['mark'];
        if (!$type) {
            throw new Exception('请设置广告位标示');
        }

        if (false === $name) {
            $name = md5(serialize($options));
        }

        if (true === $name || !isset(self::$instance[$name])) {
            $class = false === strpos($type, '\\') ?
                '\\app\\common\\logic\\ad\\driver\\' . ucwords($type) :
                $type;

            if (true === $name) {
                return new $class($options);
            }

            self::$instance[$name] = new $class($options);
        }

        return self::$instance[$name];
    }

    /**
     * 初始化
     * @access public
     * @param  array $options 配置数组
     * @return Driver
     */
    public static function init(array $options = [], $reload = false)
    {
        if (is_null(self::$handler) || $reload == true) {

            self::$handler = self::create($options, $reload);
        }

        return self::$handler;
    }




    /**
     * 判断缓存是否存在
     * @access public
     * @param  array $data 配置数组
     * @return boolean
     */
    public function add($data) {
        return self::$handler->add($data);
    }


    public static function getRandAds($tag) {
        $ad = new Ads();
        $cast_item_id = Db::name('self_cast_item')->where(['tag'=> $tag])->value('id');
        $item = $ad->where(['switch'=> 1])
            ->where('id', 'in', function ($query) use ($cast_item_id) {
            $query->name('self_ad_rule')
                ->whereOr(['mark'=>'cast'])
                ->where(['cast_item_id' => ['in', [$cast_item_id, 0]]])->field('ad_ads_id');
        })->orderRaw('rand()')->find();

        return $item;
    }

    //获取多条广告
    public static function getRandMany($tag, $limit = 1) {
        $ad = new Ads();
        $cast_item_id = Db::name('self_cast_item')->where(['tag'=> $tag])->value('id');
        $item = $ad->where(['switch'=> 1])->where('id', 'in', function ($query) use ($cast_item_id) {
            $query->name('self_ad_rule')
                ->whereOr(['mark'=>'cast'])
                ->where(['cast_item_id' => ['in', [$cast_item_id, 0]]])->field('ad_ads_id');
        })->orderRaw('rand()')->limit($limit)->select();

        return $item;
    }
}